<!---------------------新增修改商品信息-------------------->
<template>
    <el-dialog :close-on-click-modal="false" v-model="visible" @close="handleClose" title="商品信息" destroy-on-close
        fullscreen class="full-dialog">
        <el-scrollbar style="height: calc(100vh - 145px)" v-loading="loading">
            <div class="mx-4 my-8">
                <!---------------------基本信息开始-------------------->
                <el-form ref="formRef" :model="form" label-position="right" label-width="120px" :rules="rules">
                    <el-row :gutter="20">
                        <el-form-item label="采购员" prop="admin_name">
                            <el-select v-model="form.admin_name" class="w-full" placeholder="请选择采购员" :disabled="$props.status === 2 || $props.status === 3"
                                @change="changeAdmin"><el-option v-for="item in $props.purchaserList" :value="item.id"
                                    :key="item.id" :label="item.nickname"></el-option></el-select>
                        </el-form-item>
                        <el-form-item label="采购日期" prop="purchase_time">
                            <el-date-picker v-model="form.purchase_time" type="date" placeholder="请选择日期" :disabled="$props.status === 2 || $props.status === 3"
                                value-format="YYYY-MM-DD" class="ml-2 w-52" />
                        </el-form-item>
                        <el-form-item label="运费" prop="freight">
                            <el-input v-model="form.freight" @input="(val) => {form.freight = inputNumber(val)}" :disabled="$props.status === 2 || $props.status === 3" />
                        </el-form-item>
                        <el-form-item label="物流单号" prop="express">
                            <el-input v-model="form.express" :disabled="$props.status === 2 || $props.status === 3" />
                        </el-form-item>
                        <el-form-item label="入库仓库" prop="warehouseShelfId" v-if="$props.status === 2 || $props.status === 3">
                            <el-cascader
                                :disabled="$props.status === 3"
                                v-model="form.warehouseShelfId"
                                :options="warehouseList"
                                :props="{ expandTrigger: 'hover', label: 'name', value: 'id', children: 'children' }"
                                class="w-full"
                            />
                        </el-form-item>
                        <el-col :span="24">
                            <el-form-item label="采购明细">
                                <Product ref="productRef" :status="$props.status" :platform="$props.platform" :isEdit="true" :data="data"
                                 :purchaserList="$props.purchaserList" @updateData="updateData">
                                </Product>
                            </el-form-item>
                        </el-col>
                        <el-form-item label="采购总量" prop="sum">
                            <el-input v-model="form.sum" disabled />
                        </el-form-item>
                        <el-form-item label="采购总金额(¥)" prop="money">
                            <el-input v-model="form.money" disabled />
                        </el-form-item>
                        <el-col :span="24">
                            <el-form-item label="凭证图片" prop="image">
                                <ImgHub v-model="form.image" :limit="1" :disabled="$props.status === 2 || $props.status === 3" :deleteAll="false" :multiple="false"></ImgHub>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" :disabled="$props.status === 2 || $props.status === 3" type="textarea" row="5" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

        </el-scrollbar>

        <template #footer>
            <el-button @click="handleClose"><el-icon class="mr-1 text-slate-500">
                    <CloseBold />
                </el-icon> 取消</el-button>
            <el-button type="primary" @click="offlineProcessing" v-if="$props.status === 3">
                线下处理
            </el-button>
            <el-button type="primary" @click="handleSave">
                <Icon name="fa fa-save" class="mr-1 text-white text-base"></Icon> 保存
            </el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { watch, ref, reactive, provide, nextTick, onMounted } from 'vue'
import createAxios from '/@/utils/axios'
import { ElMessage } from 'element-plus'
import { Plus, Delete, CloseBold } from '@element-plus/icons-vue'
import { baTableApi } from '/@/api/common'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import ImgHub from '/@/components/imgHub/index.vue'
import lo from 'lodash'
import { inputNumber } from '/@/utils/tools'
import Product from '/@/components/product/product.vue'

const props = defineProps({
    modelValue: Boolean, //是否打开弹窗
    data: Object, //数据
    platform: Number, //平台id
    status: Number, //1添加与编辑 2入库 3异常处理
    purchaserList: {type: Array, default: []}, //采购人列表
    purchaserIndex: {type: Number, default: -1 }, //采购人索引
})
let visible = ref(false) //弹层组件内部控制显隐
const rules = reactive({
    admin_name: [{ required: true, message: '请选择采购员', trigger: 'change' }],
    purchase_time: [{ type: 'date', required: true, message: '请选择采购日期', trigger: 'change' }],
    freight: [{ required: true, message: '请输入运费', trigger: 'blur' }],
    image: [{ required: true, message: '请选择凭证图片', trigger: 'change' }],
    warehouseShelfId: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
}) // 表单规则
let form = ref({
    admin_id: '', // 采购员id
    admin_name: '', //采购员名称
    purchase_time: '', // 采购日期
    freight: '', // 运费
    express: '',
    sum: 0, //采购总量
    money: 0, //采购总金额
    remark: '', // 备注
    image: [], //凭证图片
    detail_json: '', //采购明细json ["order_product_no 采购编号","product_id 采购产品ID","actual_quantity 实际数量","plan_quantity 计划数量","price 采购单价","total_price 总金额","remark 单个备注","product_title 商品标题"]
    warehouseShelfId: []
}) // 表单数据
let formRef: any = ref() // 表单实例
let loading: any = ref(false) // 表单加载状态
let coverImgList: any = ref([]) // 封面图
let skuList: any = ref([]) // SKU库存列表
const tableRef = ref()
const productRef = ref()
const dateDetail: any = ref([]) //商品明细详情
const purchase_no: any = ref('') //编辑时的订单id

let warehouse: any = ref('')
let warehouseList: any = ref([]) //仓库列表

watch(
    () => props.purchaserIndex,
    (newVal) => {
        if(!props.data?.id && newVal !== -1 && props.purchaserList) {
            //创建时赋值
            form.value.admin_name = props.purchaserList[newVal].nickname;
            form.value.admin_id = props.purchaserList[newVal].id;
        }
    }
);

watch(
    () => props.status,
    (newVal) => {
        if(newVal === 2 || newVal === 3) {
            getWarehouseList()
        }
    }
);

// 监听弹层显示隐藏
watch(
    () => props.modelValue,
    (val) => {
        visible.value = val
        if (val) {
            nextTick(async () => {
                formRef.value.resetFields()
                if (props.data?.id) {
                    await getProductInfo()
                }
            })
        } else {
            loading.value = false
            form.value = {
                admin_id: '', // 采购员id
                admin_name: '', //采购员名称
                purchase_time: '', // 采购日期
                freight: '', // 运费
                express: '',
                sum: 0, //采购总量
                money: 0, //采购总金额
                remark: '', // 备注
                image: [], //凭证图片
                detail_json: '', //采购明细
                warehouseShelfId: []
            } // 表单数据
            coverImgList.value = [] // 封面图
            skuList.value = [] // SKU库存列表
        }
    }
)

const emits = defineEmits(['close', 'update'])

//改变采购员
const changeAdmin = (val: any) => {
    form.value.admin_id = val
}

//关闭操作
const handleClose = () => {
    emits('close', false) // 可以更新 v-model 绑定的值
}

//更新商品明细数据
const updateData = (date: any) => {
    form.value.sum = 0
    form.value.money = 0
    dateDetail.value = date
    dateDetail.value.forEach((item: any) => {
        item.sku_list.forEach((sku_item: any) => {
            if (sku_item.actual_quantity) {
                form.value.sum += +sku_item.actual_quantity
            }
            if (sku_item.price) {
                form.value.money += +sku_item.price * +sku_item.actual_quantity
            }
        });
    });
}

//保存操作
const handleSave = async () => {
    await formRef.value.validate(async (valid: any) => {
        if (valid) {
            //检查采购明细是否存在空值
            let a = 0
            dateDetail.value.forEach((item: any) => {
                let flag = false
                if(props.status === 2 || props.status === 3) {
                    flag = item.sku_list.some((sku_item: any) => !sku_item.actual_quantity.toString().trim() || !sku_item.price.toString().trim() || !sku_item.plan_quantity.toString().trim());
                } else {
                    flag = item.sku_list.some((sku_item: any) => !sku_item.actual_quantity.toString().trim() || !sku_item.price.toString().trim());
                }
                
                if (flag) {
                    a += 1
                }
            })
            if (a != 0) {
                ElMessage({ type: 'error', message: '请检查采购明细数据是否存在未填的值' })
                return
            }
            let url
            let params: any = {}
            if(props.status === 3) {
                params = {
                    admin_id: form.value.admin_id,
                    purchase_time: form.value.purchase_time,
                    freight: form.value.freight,
                    express: form.value.express,
                    sum: form.value.sum,
                    money: form.value.money,
                    remark: form.value.remark,
                    image: form.value.image.join(','),
                    detail_json: JSON.stringify(dateDetail.value),
                    platform: props.platform,
                    id: '',
                    order_product_no: '',
                    warehouse_shelf_id: '',
                    status: 2
                }
            } else {
                params = {
                    admin_id: form.value.admin_id,
                    purchase_time: form.value.purchase_time,
                    freight: form.value.freight,
                    express: form.value.express,
                    sum: form.value.sum,
                    money: form.value.money,
                    remark: form.value.remark,
                    image: form.value.image.join(','),
                    detail_json: JSON.stringify(dateDetail.value),
                    platform: props.platform,
                    id: '',
                    order_product_no: '',
                    warehouse_shelf_id: ''
                }
            }
            if(props.status === 2) {
                //入库
                url = '/admin/xmwms.purchase.Order/storage'
                params.warehouse_shelf_id = form.value.warehouseShelfId.join(',')
                params.id = props.data?.id
                params.order_product_no = purchase_no.value
            } else if (props.status === 3) {
                //处理异常
                url = '/admin/xmwms.purchase.Order/abnormal_status'
                params.warehouse_shelf_id = form.value.warehouseShelfId.join(',')
                params.id = props.data?.id
                params.order_product_no = purchase_no.value
            }  else if (props.data?.id) {
                //编辑
                url = '/admin/xmwms.purchase.Order/edit'
                params.id = props.data.id
                params.order_product_no = purchase_no.value
            } else {
                //添加
                url = '/admin/xmwms.purchase.Order/add'
            }
            await createAxios({ url: url, method: 'post', data: params })
                .then((res) => {
                    if (res.code === 1) {
                        ElMessage({ type: 'success', message: res.msg })
                        emits('update')
                        handleClose()
                    } else {
                        ElMessage({ type: 'error', message: res.msg })
                    }
                })
                .finally(() => {
                    loading.value = false
                })
        } else {

        }
    })
}

// 获取商品ID获取商品信息
const getProductInfo = () => {
    loading.value = true
    let url = ''
    if(props.status === 3) {
        url = '/admin/xmwms.purchase.Order/abnormal_detail'
    } else {
        url = '/admin/xmwms.purchase.Order/detail'
    }
    createAxios({ url, method: 'get', params: { id: props.data?.id } }).then((res) => {
        if (res.code === 1) {
            let base_data = res.data
            //给子组件已有商品赋值
            productRef.value.data = base_data.detail

            purchase_no.value = base_data.purchase_no

            //获取采购员名称
            form.value.admin_id = base_data.admin_id
            let resultItem: any = props.purchaserList?.find((item: any) => {
                return item.id == base_data.admin_id
            })

            form.value.admin_name = resultItem?.nickname

            form.value.purchase_time = base_data.purchase_time
            form.value.freight = base_data.freight
            form.value.express = base_data.express
            form.value.remark = base_data.remark
            form.value.image = base_data.image.split(',')
            form.value.warehouseShelfId = base_data.warehouse_shelf_id ? lo.map(base_data.warehouse_shelf_id.split(','), lo.unary(parseInt)) : [], //仓库,分割成数组,再把数组里面每一项转成数字
            console.log( form.value.warehouseShelfId," form.value.warehouseShelfId");
            

            //采购数量单价赋值
            base_data.detail.forEach((item: any) => {
                item.skus.forEach((sku_item: any) => {
                    if (sku_item.actual_quantity) {
                        form.value.sum += +sku_item.actual_quantity
                    }
                    if (sku_item.price) {
                        form.value.money += +sku_item.price * +sku_item.actual_quantity
                    }
                });
            });

            dateDetail.value = []
            let oldDateDetail: any = []
            //采购明细赋值
            base_data.detail.forEach((item:any,index:any) => {
                dateDetail.value.push({
                    product_id: item.id,
                    product_title: item.title,
                    remark: item.remark,
                    thumb: item.thumb,
                    money_price: item.money_price,
                    sku_list: []
                })
                item.skus.forEach((sku_item: any) => {
                    dateDetail.value[index].sku_list.push({
                        demand_sku_id: sku_item.demand_sku_id,
                        detail_id:sku_item.detail_id,
                        uuid:sku_item.uuid,
                        xq_id: sku_item.xq_id,
                        plan_quantity: sku_item.plan_quantity,
                        actual_quantity: sku_item.actual_quantity,
                        price: sku_item.price,
                        sku_title: sku_item.title,
                        money_price: sku_item.money_price,
                        thumb: sku_item.thumb
                    })
                    oldDateDetail.push({
                        demand_sku_id: sku_item.demand_sku_id,
                        detail_id: sku_item.detail_id,
                    })
                });
            });
            productRef.value.dateDetail = dateDetail.value
            
            productRef.value.oldDateDetail = oldDateDetail
            
            loading.value = false
        }
    })
}

//获取仓库列表
const getWarehouseList = () => {
    createAxios({ url: '/admin/xmwms.Warehouse/select', method: 'get' }).then((res) => {
        if (res.code === 1) {
            warehouseList.value = res.data.options
        }
    })
}

//线下处理
const offlineProcessing = () => {
    loading.value = true
    createAxios({ url: '/admin/xmwms.purchase.Order/abnormal_status', method: 'get', params: { status: 1 , id: props.data?.id } })
        .then((res) => {
            if (res.code === 1) {
                ElMessage({ type: 'success', message: res.msg })
                emits('update')
                handleClose()
            } else {
                ElMessage({ type: 'error', message: res.msg })
            }
        })
        .finally(() => {
            loading.value = false
        })
}

onMounted(() => {
    // baTable.table.ref = tableRef.value
    // baTable.mount()
    // baTable.getXqList()?.then(() => {
    //     baTable.initSort()
    //     baTable.dragSort()
    // })
})
</script>
